import requests
import json
import os


def get_list(max_pages=5, page_size=10):
    """
    分页获取酒店列表数据
    
    Args:
        max_pages (int): 最大获取页数，默认5页
        page_size (int): 每页数据量，默认10条
    
    Returns:
        list: 所有获取到的酒店数据列表
    """
    url = "https://m.ctrip.com/restapi/soa2/31454/json/fetchHotelList"
    
    # 设置请求头
    headers = {
        'Content-Type': 'application/json;charset=UTF-8',
        'origin': 'https://hotels.ctrip.com',
        'referer': 'https://hotels.ctrip.com/',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
        'phantom-token': '1004-common-d7SeozimHrM3Y3DiGbvL3Jo6jlOYThYLFj3FykoW4litMv0tv1gR6pvmAv9ZEfsy1oJkAEPHEsbE0TEcpYG6RNFELdypbEcAy5zv3XvQaWOke5UKXDJ3Y97eMzY1XvToRtoysqJZ8YMgjLtE5fYUFETFyXbwqcjmBWh5WBSIp7wl3jqY8txfwqTK94KHPjNMj3tEFZyoE9hiNFYlEPzYl6y3EhSY9Qy8DKqMigkj1SjkQWMoyAOIUQwSQjhmw5NehOELqI4Sw7miFlRlEZ0YGTygmKsQiD9ja7jFPW3lyNEfcYg5ysDWZNenZyONjFGY6PE4gxUHjoEdniBpy7nwPnehQjsbIksjqDYzNEdXRb0jFEZai90JM0KbNEtTYHzxN0rzfKgzicnv1Em9YNDwoQw1PepSjhzItE63il0JFfRB3ygESFYncwa4iSMEAkjDQeBkiHFYhzxBzy9EBQipSJ36RLHykEZkYzhwh3i3BElbjZFe5simBY4lwZSIAHElzjoEfgiBaJZXEaSep4j8cI9Et5YqdwdPwXoKNZjMnwAQrOTeGSYUEOhiagJGMYTnWLcYa1JkEn3YzFya9WASyBEoOYQGyMTRtAjnEz6Y5OwSGwmQKaqjX4w5prk7ibnvsmjtE8Bi3cJt7Y50WHDYz8JfE4dYpqyFLWmByXEbkYcsy4hR6Sv8hwhte16Y6YQdKH9Kgoe31RQcyNnEAtv7Pw8gYH7jUpyNawSaJz7RpBy3tjZTI8oikoEsov7DjkXi1TemHyTtKlkyUgRcXj1ARaTR6OY6ojFYGsIc6WmDeG1jFav6DEkqWdLJ4Oybgw9HiUXegaJc8E87R4Aw1Oek5EfOY09WXfySsekNEFdETdJM8iT5eb4E9Pvn1vcpYtsyfTjoAWFcwoNv9FRcmy1kjU3J16JTNjfYsarGBvsGw7gEcsE4oYFPwcFwMLJ1gYaSw5sR34eL8RHYTFjd6ip0y0BYHAEzNIBsxf9roYNGYS6KL9ebfvB7eNHYpoi1nY9dvqGromrPYphRtFYotr0seZNElzjBaWbvctRtmEkYsOyB3EmGEANr5GKcLeTmEa0W1AwAQynEBYhAybqrSAwPsRsXvzHYL7W8LeO8R3bWGOjgcWlHvcTEbaJqYfzekLY8HE7lRfmv1ZYLhWfLedcRspW8UinhYXjQ7e3GRzY0TIbDi8NIMsJOXWLDWDqK0XW8Ay9Y0pw1HEQ5rAoYqLiS7w7HRnXEoUWADxQArktKHYa1wqSyoj5oJTyUJ3gEpYD0INSrUfWp7jaswHGvBNjAajs6WaPeUYh5KoOwZZKtgYkXJ6bjlswFYQXYtSYbkY3hjPcwQMv0HjQcK4OrbBv1YHPIk4w9LKcXJ6LWBsYhNe1QwZYkXI4GYS8eQ5jlmitcif5xDsW8pjTrBbx4nY3bwT1I5r9yosYdorXzJfj68R8SRfwoYd6YkfJSAIqURozWQcY6zWkgWbmYlMIbzIDn',
        'cookie': '_RGUID=d3cf2739-7d52-49c7-83ca-d6912d10ec2d; _RSG=7daKzbp9FFDjmE4j4frAF8; _RDG=28bc8f92ec899723e213b6362634f7220a; ibulanguage=CN; ibulocale=zh_cn; cookiePricesDisplayed=CNY; UBT_VID=1749628765178.34f8BidwFO8O; GUID=09031023418324712277; nfes_isSupportWebP=1; MKT_CKID=1751951812488.2nrur.zh83; cticket=18928CB4DB1885336BC4FBE53C021ACDB1AAA6C9FFA9EE5A69A4C5C1EB93B08C; login_type=0; login_uid=E6E8B77C50B1EEE6F9AEB5FB0EAF019A; DUID=u=E6E8B77C50B1EEE6F9AEB5FB0EAF019A&v=0; IsNonUser=F; AHeadUserInfo=VipGrade=5&VipGradeName=%B0%D7%D2%F8%B9%F3%B1%F6&UserName=&NoReadMessageCount=0; _udl=708D70C2B179E2F91CC5ED1C2CCE362D; librauuid=; _RF1=125.121.189.180; intl_ht1=h4=17_122247884,17_78503851,17_124837246,17_479445,17_1379529; _bfa=1.1749628765178.34f8BidwFO8O.1.1752842466810.1752843720293.17.5.102002; _jzqco=%7C%7C%7C%7C%7C1.985324806.1751951812481.1752842467252.1752843721215.1752842467252.1752843721215.0.0.0.58.58'
    }
    
    all_hotels = []  # 存储所有酒店数据
    hotel_ids_shown = []  # 存储已获取的酒店ID，用于去重
    
    for page_index in range(1, max_pages + 1):
        print(f"正在获取第 {page_index} 页数据...")
        
        # 构建请求体
        body = {
            "hotelIdFilter": {"hotelAldyShown": hotel_ids_shown},
            "destination": {
                "type": 1,
                "geo": {"cityId": 17, "countryId": 1},
                "keyword": {"word": ""}
            },
            "date": {
                "dateType": 1,
                "dateInfo": {"checkInDate": "20250714", "checkOutDate": "20250814"}
            },
            "filters": [{"filterId": "29|1", "type": "29", "value": "1|1", "subType": "2"}],
            "extraFilter": {"childInfoItems": [], "sessionId": ""},
            "paging": {"pageCode": "102002", "pageIndex": page_index, "pageSize": page_size},
            "roomQuantity": 1,
            "recommend": {"nearbyHotHotel": {}},
            "genk": True,
            "residenceCode": "CN",
            "head": {
                "platform": "PC",
                "cid": "09031023418324712277",
                "cver": "hotels",
                "bu": "HBU",
                "group": "ctrip",
                "aid": "",
                "sid": "",
                "ouid": "",
                "locale": "zh-CN",
                "timezone": "8",
                "currency": "CNY",
                "pageId": "102002",
                "vid": "1749628765178.34f8BidwFO8O",
                "guid": "09031023418324712277",
                "isSSR": False
            },
            "ServerData": ""
        }
        
        try:
            response = requests.post(url, json=body, headers=headers)
            response.raise_for_status()  # 检查HTTP错误
            
            data = response.json()
            
            # 检查响应数据结构
            if 'data' not in data or 'hotelList' not in data['data']:
                print(f"第 {page_index} 页数据格式异常，跳过")
                continue
                
            hotel_list = data['data']['hotelList']
            
            if not hotel_list:
                print(f"第 {page_index} 页没有更多数据，停止获取")
                break
                
            # 提取酒店ID并添加到过滤列表
            page_hotel_ids = []
            for hotel in hotel_list:
                if ('hotelInfo' in hotel and 
                    'summary' in hotel['hotelInfo'] and 
                    'hotelId' in hotel['hotelInfo']['summary']):
                    hotel_id = hotel['hotelInfo']['summary']['hotelId']
                    page_hotel_ids.append(hotel_id)
                    
            # 更新已显示的酒店ID列表
            hotel_ids_shown.extend(page_hotel_ids)
            
            # 添加到总列表
            all_hotels.extend(hotel_list)
            
            print(f"第 {page_index} 页获取成功，本页 {len(hotel_list)} 家酒店，累计 {len(all_hotels)} 家酒店")
            print(f"本页酒店ID: {page_hotel_ids}")
            
        except requests.exceptions.RequestException as e:
            print(f"第 {page_index} 页请求失败: {e}")
            break
        except json.JSONDecodeError as e:
            print(f"第 {page_index} 页JSON解析失败: {e}")
            break
        except Exception as e:
            print(f"第 {page_index} 页处理异常: {e}")
            break
    
    # 保存所有数据到文件
    asset_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'asset')
    os.makedirs(asset_dir, exist_ok=True)
    
    # 保存完整数据
    all_data = {
        "total_hotels": len(all_hotels),
        "pages_fetched": len([h for h in all_hotels]) // page_size + (1 if len(all_hotels) % page_size > 0 else 0),
        "hotel_ids": hotel_ids_shown,
        "data": {
            "hotelList": all_hotels
        }
    }
    
    data_file = os.path.join(asset_dir, 'data_copy.json')
    with open(data_file, 'w', encoding='utf-8') as f:
        json.dump(all_data, f, ensure_ascii=False, indent=2)
    
    print(f"\n=== 数据获取完成 ===")
    print(f"总共获取 {len(all_hotels)} 家酒店")
    print(f"数据已保存到: {data_file}")
    
    return all_hotels






if __name__ == "__main__":
    get_list()